from typing import Optional, List
from pydantic import BaseModel, Field, validator
from datetime import datetime
from app.shared.constants.enums import AlertLevel, AlertType, NotificationType


class AlertRuleBase(BaseModel):
    """告警规则基础信息"""
    rule_name: str = Field(..., min_length=1, max_length=100, description="规则名称")
    description: Optional[str] = Field(None, max_length=500, description="规则描述")
    alert_type: AlertType = Field(..., description="告警类型")
    level: AlertLevel = Field(..., description="告警级别")
    is_enabled: bool = Field(True, description="是否启用")
    condition_expression: str = Field(..., description="条件表达式")
    notification_template: Optional[str] = Field(None, description="通知模板")
    notification_types: List[NotificationType] = Field(..., description="通知方式")
    notification_recipients: List[str] = Field(..., description="通知接收人")
    check_interval: int = Field(60, ge=30, le=3600, description="检查间隔(秒)")
    max_alert_frequency: int = Field(300, ge=60, description="最大告警频率(秒)")


class AlertRuleCreate(AlertRuleBase):
    """创建告警规则"""
    device_types: Optional[List[str]] = Field(None, description="适用设备类型")
    locations: Optional[List[str]] = Field(None, description="适用位置")


class AlertRuleUpdate(BaseModel):
    """更新告警规则"""
    rule_name: Optional[str] = Field(None, min_length=1, max_length=100, description="规则名称")
    description: Optional[str] = Field(None, max_length=500, description="规则描述")
    level: Optional[AlertLevel] = Field(None, description="告警级别")
    is_enabled: Optional[bool] = Field(None, description="是否启用")
    condition_expression: Optional[str] = Field(None, description="条件表达式")
    notification_template: Optional[str] = Field(None, description="通知模板")
    notification_types: Optional[List[NotificationType]] = Field(None, description="通知方式")
    notification_recipients: Optional[List[str]] = Field(None, description="通知接收人")
    check_interval: Optional[int] = Field(None, ge=30, le=3600, description="检查间隔(秒)")
    max_alert_frequency: Optional[int] = Field(None, ge=60, description="最大告警频率(秒)")
    device_types: Optional[List[str]] = Field(None, description="适用设备类型")
    locations: Optional[List[str]] = Field(None, description="适用位置")


class AlertRuleResponse(AlertRuleBase):
    """告警规则响应"""
    id: int = Field(..., description="规则ID")
    device_types: Optional[List[str]] = Field(None, description="适用设备类型")
    locations: Optional[List[str]] = Field(None, description="适用位置")
    created_by: int = Field(..., description="创建人ID")
    created_by_name: Optional[str] = Field(None, description="创建人姓名")
    created_at: datetime = Field(..., description="创建时间")
    updated_at: datetime = Field(..., description="更新时间")
    last_triggered_at: Optional[datetime] = Field(None, description="最后触发时间")
    trigger_count: int = Field(0, description="触发次数")
    
    class Config:
        from_attributes = True


class AlertBase(BaseModel):
    """告警基础信息"""
    title: str = Field(..., description="告警标题")
    content: str = Field(..., description="告警内容")
    level: AlertLevel = Field(..., description="告警级别")
    alert_type: AlertType = Field(..., description="告警类型")
    source_data: Optional[dict] = Field(None, description="源数据")


class AlertCreate(AlertBase):
    """创建告警"""
    device_id: Optional[int] = Field(None, description="设备ID")
    rule_id: Optional[int] = Field(None, description="告警规则ID")


class AlertUpdate(BaseModel):
    """更新告警"""
    is_resolved: bool = Field(..., description="是否已解决")
    resolved_by: Optional[int] = Field(None, description="解决人ID")
    resolution_notes: Optional[str] = Field(None, max_length=1000, description="解决备注")


class AlertResponse(AlertBase):
    """告警响应"""
    id: int = Field(..., description="告警ID")
    alert_number: str = Field(..., description="告警编号")
    device_id: Optional[int] = Field(None, description="设备ID")
    device_code: Optional[str] = Field(None, description="设备编码")
    device_name: Optional[str] = Field(None, description="设备名称")
    rule_id: Optional[int] = Field(None, description="告警规则ID")
    rule_name: Optional[str] = Field(None, description="告警规则名称")
    is_resolved: bool = Field(..., description="是否已解决")
    resolved_by: Optional[int] = Field(None, description="解决人ID")
    resolved_by_name: Optional[str] = Field(None, description="解决人姓名")
    resolved_at: Optional[datetime] = Field(None, description="解决时间")
    resolution_notes: Optional[str] = Field(None, description="解决备注")
    created_at: datetime = Field(..., description="创建时间")
    updated_at: datetime = Field(..., description="更新时间")
    
    class Config:
        from_attributes = True


class AlertListQuery(BaseModel):
    """告警列表查询"""
    page: int = Field(1, ge=1, description="页码")
    page_size: int = Field(20, ge=1, le=100, description="每页数量")
    search: Optional[str] = Field(None, description="搜索关键词")
    level: Optional[AlertLevel] = Field(None, description="告警级别筛选")
    alert_type: Optional[AlertType] = Field(None, description="告警类型筛选")
    device_id: Optional[int] = Field(None, description="设备ID筛选")
    is_resolved: Optional[bool] = Field(None, description="是否已解决筛选")
    rule_id: Optional[int] = Field(None, description="告警规则ID筛选")
    start_date: Optional[datetime] = Field(None, description="开始日期")
    end_date: Optional[datetime] = Field(None, description="结束日期")
    sort_by: Optional[str] = Field("created_at", description="排序字段")
    sort_order: Optional[str] = Field("desc", regex=r'^(asc|desc)$', description="排序方向")


class AlertRuleListQuery(BaseModel):
    """告警规则列表查询"""
    page: int = Field(1, ge=1, description="页码")
    page_size: int = Field(20, ge=1, le=100, description="每页数量")
    search: Optional[str] = Field(None, description="搜索关键词")
    alert_type: Optional[AlertType] = Field(None, description="告警类型筛选")
    level: Optional[AlertLevel] = Field(None, description="告警级别筛选")
    is_enabled: Optional[bool] = Field(None, description="是否启用筛选")
    sort_by: Optional[str] = Field("created_at", description="排序字段")
    sort_order: Optional[str] = Field("desc", regex=r'^(asc|desc)$', description="排序方向")


class NotificationChannelBase(BaseModel):
    """通知渠道基础信息"""
    channel_name: str = Field(..., min_length=1, max_length=100, description="渠道名称")
    channel_type: NotificationType = Field(..., description="通知类型")
    is_enabled: bool = Field(True, description="是否启用")
    configuration: dict = Field(..., description="渠道配置")


class NotificationChannelCreate(NotificationChannelBase):
    """创建通知渠道"""
    pass


class NotificationChannelUpdate(BaseModel):
    """更新通知渠道"""
    channel_name: Optional[str] = Field(None, min_length=1, max_length=100, description="渠道名称")
    is_enabled: Optional[bool] = Field(None, description="是否启用")
    configuration: Optional[dict] = Field(None, description="渠道配置")


class NotificationChannelResponse(NotificationChannelBase):
    """通知渠道响应"""
    id: int = Field(..., description="渠道ID")
    created_by: int = Field(..., description="创建人ID")
    created_at: datetime = Field(..., description="创建时间")
    updated_at: datetime = Field(..., description="更新时间")
    last_used_at: Optional[datetime] = Field(None, description="最后使用时间")
    success_count: int = Field(0, description="成功发送次数")
    failure_count: int = Field(0, description="失败发送次数")
    
    class Config:
        from_attributes = True


class NotificationLogResponse(BaseModel):
    """通知日志响应"""
    id: int = Field(..., description="日志ID")
    alert_id: int = Field(..., description="告警ID")
    channel_id: int = Field(..., description="通知渠道ID")
    channel_name: str = Field(..., description="通知渠道名称")
    channel_type: NotificationType = Field(..., description="通知类型")
    recipient: str = Field(..., description="接收人")
    content: str = Field(..., description="通知内容")
    is_success: bool = Field(..., description="是否成功")
    error_message: Optional[str] = Field(None, description="错误信息")
    sent_at: datetime = Field(..., description="发送时间")
    
    class Config:
        from_attributes = True


class AlertStatistics(BaseModel):
    """告警统计"""
    total_count: int = Field(..., description="总告警数")
    unresolved_count: int = Field(..., description="未解决告警数")
    resolved_count: int = Field(..., description="已解决告警数")
    critical_count: int = Field(..., description="严重告警数")
    high_count: int = Field(..., description="高级告警数")
    avg_resolution_time: Optional[float] = Field(None, description="平均解决时长(小时)")
    resolution_rate: float = Field(..., description="解决率")
    by_type: Dict[str, int] = Field(..., description="按类型分组")
    by_level: Dict[str, int] = Field(..., description="按级别分组")


class AlertBatchOperation(BaseModel):
    """告警批量操作"""
    alert_ids: List[int] = Field(..., min_items=1, description="告警ID列表")
    operation: str = Field(..., description="操作类型")
    params: Optional[dict] = Field(None, description="操作参数")


class TestAlertRequest(BaseModel):
    """测试告警请求"""
    rule_id: int = Field(..., description="告警规则ID")
    test_data: Optional[dict] = Field(None, description="测试数据")